<?php
class unitofwork
{
    //可以在这里的__construct() 方法中把所有状态isdelete isupdate isdelete全部置为false  这样貌似行不通
    public function commit()
    {
        $this->buildinsertstatement();
        $this->builddeletestatement();
        $this->buildupdatestatement();
    }

    public function buildinsertstatement()
    {
        $entitylist = entityrepo::getinsertlist();
        foreach($entitylist as $entity)
        {
            $fields = $entity->getfields();
            $classname = get_class($entity);
            $sql = "insert into $classname"; 
            $columns = array();
            $columnvalues = array();
            $binds = array();
            foreach($fields as $name => $value)
            {
                $columns[] = $name;
                $columnvalues[] = ":$name";
                $binds[":$name"] = $entity->$name; 
            }
            $column_str = implode(', ', $columns);
            $columnvalue_str = implode(', ', $columnvalues);

            $sql .= "($column_str) values($columnvalue_str)";
            matrix::get('dbexecuter')->execute($sql, $binds);
            entityrepo::delete($entity);
        }
    }

    public function buildupdatestatement()
    {
        $entitylist = entityrepo::getupdatelist();
        foreach($entitylist as $entity)
        {
            $fields = $entity->getfields();
            $classname = get_class($entity);
            $sql = "update $classname set"; 
            $binds = array();
            $updates = array();
            foreach($fields as $name => $value)
            {
                if('id' == $name) continue;
                $updates[] = " $name = :$name ";
                $binds[":$name"] = $entity->$name; 
            }
            $binds[':id'] = $entity->id;
            $update_str = implode(', ', $updates);
            $sql .= "$update_str where id = :id";
            matrix::get('dbexecuter')->execute($sql, $binds);
            entityrepo::delete($entity);
        }
    }

    public function builddeletestatement()
    {
        $entitylist = entityrepo::getdeletelist();
        foreach($entitylist as $entity)
        {
            $fields = $entity->getfields();
            $classname = get_class($entity);
            $sql = "delete from $classname where id = :id"; 
            $binds[':id'] = $entity->id;
            matrix::get('dbexecuter')->execute($sql, $binds);
            entityrepo::delete($entity);
        }
    }
}
